<template>
  <div class="editor-page">
    <article-editor
      :article-info="articleInfo"
      @add-article="add = true"
    ></article-editor>
  </div>
</template>

<script>
import { api } from "@/api";
import ArticleEditor from "@/components/editor/ArticleEditor.vue";
export default {
  components: { ArticleEditor },
  data() {
    return {
      articleInfo: {},
      add: false,
    };
  },
  addArticle() {
    this.add = true;
  },
  beforeRouteLeave(to, from, next) {
    if (this.add) {
      next();
      return;
    }
    const answer = window.confirm("未保存的内容不会被保留，你确定离开吗?");
    if (answer) {
      next();
    } else {
      next(false);
    }
  },
  methods: {
    async getArticleInfoById() {
      try {
        if (this.$route.query.id) {
          this.articleInfo = (
            await this.$axios(
              api.article.getArticleContent(this.$route.query.id)
            )
          ).data;
        }
      } catch (error) {
        this.loading = false;
        if (error.response) {
          this.$alert(error.response.data.message);
        } else {
          this.$alert("网络错误");
        }
      }
    },
    guard() {
      let _this = this;
      window.onbeforeunload = function (e) {
        if (_this.$route.path == "/editor") {
          e = e || window.event;
          // 兼容IE8和Firefox 4之前的版本
          if (e) {
            e.returnValue = "关闭提示";
          }
          // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
          return "关闭提示";
        } else {
          window.onbeforeunload = null;
        }
      };
    },
  },
  mounted() {
    this.getArticleInfoById();
    this.guard();
  },
};
</script>

<style lang="less" scoped></style>
